package com.czxy.tanhua.autoconfig.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.czxy.tanhua.autoconfig.properties.OssProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author 爱吃豆的土豆、
 * @Date 2023/3/31 9:49
 */
@Component
public class OssTemplate {
    private OssProperties ossProperties;

    public OssTemplate(OssProperties properties) {
        this.ossProperties = properties;
    }

    public String upload(MultipartFile file) {
        if(file == null) {
            throw new RuntimeException("上传文件为空");
        }
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getKeyId(), ossProperties.getKeySecret());
            String path = ossProperties.getDirName() + "/" + System.currentTimeMillis() + ".png";
            // 数据流
//            FileInputStream fileInputStream = new FileInputStream(file);
            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(ossProperties.getBucketName(), path, file.getInputStream());
            // 关闭OSSClient。
            ossClient.shutdown();
            String url = ossProperties.getPathProtocol() + "://"+ossProperties.getBucketName()+"."+ossProperties.getEndpoint()+"/" + path;
            return url;
        } catch (IOException e) {
            throw new RuntimeException("文件上传有误");
        }

    }
}
